package com.authine.cloudpivot.ext.controller.fileInfo.mainCom;

import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 *
 *  总公司级档案基层组织授权信息
 *
 **/
@RestController
@RequestMapping("/public/mainPrimaryLevelAuthInfo")
@Slf4j
public class MainPrimaryLevelAuthInfoController extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     *  总公司级档案部门授权信息  审批流完成后 数据写到基础表-总公司级档案中间组织授权信息(总公司级档案部门授权信息)
     */
    @Async
    @RequestMapping("empower")
    public void empower(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.MainPrimaryLevelAuthInfo, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("PrimaryLevelAuthInfoSheet1");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String fileCode = (String) map.get("fileCode");

            try {

                //调用存储过程
                callProcess(map, approval);

            } catch (Exception e) {
                log.info("基础表-总公司档案  添加失败 fileCode={}", fileCode);
                log.info(e.getMessage(), e);
            }

        }
    }

    /**
     *  调用存储过程
     ---------总公司级档案基层组织授权同步存储过程		----2023.03.22
     exec   SyncCorpArchiveBase
     @BaseOrgNumber  nvarchar(50),		----基层组织代码
     @Number		 nvarchar(100),		----档案代码
     @Qty			 int,				----纸质
     @DeptQty		 int,				----部门纸质
     @PosQty		 int,				----岗位纸质
     @WorkDesc		 nvarchar(200),		----工作说明
     @AuditTime		 Datetime,			----审批时间
     @Auditor		 nvarchar(50),		----审批人(员工号+姓名)
     @BasePerson	 nvarchar(50),		----基层组织责任人
     @P001			 nvarchar(10),		----001权限     1  五角    5  三角    6  对勾   7 空（取消授权）
     @Q001			 int,			----001数量
     @R001			 nvarchar(10),		----001学习要求    1  I，2 Ⅱ，3  Ⅲ
     @P002			 nvarchar(10),		----002
     @Q002			 int,
     @R002			 nvarchar(10),
     @P003			 nvarchar(10),		----003
     @Q003			 int,
     @R003			 nvarchar(10),
     @P004			 nvarchar(10),		----004
     @Q004			 int,
     @R004			 nvarchar(10),
     @P005			 nvarchar(10),		----005
     @Q005			 int,
     @R005			 nvarchar(10),
     @P006			 nvarchar(10),		----006
     @Q006			 int,
     @R006			 nvarchar(10),
     @P007			 nvarchar(10),		----007
     @Q007			 int,
     @R007			 nvarchar(10),
     @P008			 nvarchar(10),		----008
     @Q008			 int,
     @R008			 nvarchar(10),
     @P009			 nvarchar(10),		----009
     @Q009			 int,
     @R009			 nvarchar(10),
     @P010			 nvarchar(10),		----010
     @Q010			 int,
     @R010			 nvarchar(10)

     */
    private void callProcess(Map<String, Object> map, String approval){

        if (ObjectUtils.isEmpty(map)) {
            return;
        }

        log.info("入参map={}", map);

        //调用存储过程
        String AType = MapUtils.getString(map, "ShortText1670052966238", "");//档案类型
        String baseOrgNumber = MapUtils.getString(map, "baseOrgNumber", "");//基层组织代码
        String fileCode = MapUtils.getString(map, "archCodeYingshe", "");//档案代码

//        Integer totalPaper = MapUtils.getInteger(map,"totalPaper",0);//纸质
//        Integer deptPaper = MapUtils.getInteger(map, "deptPaper", 0);//部门纸质
//        Integer posPaper = MapUtils.getInteger(map, "posPaper", 0);//岗位纸质

        String totalPaperStr = map.get("totalPaper") == null ? "0" : map.get("totalPaper").toString();//纸质
        BigDecimal totalPaper = "0E-8".equals(totalPaperStr) ? new BigDecimal("0") : new BigDecimal(totalPaperStr).setScale(0, BigDecimal.ROUND_HALF_UP);
        String totalPaperValue = totalPaper.setScale(0).toString();//

        String deptPaperStr = map.get("deptPaper") == null ? "0" : map.get("deptPaper").toString();//部门纸质
        BigDecimal deptPaper = "0E-8".equals(deptPaperStr) ? new BigDecimal("0") : new BigDecimal(deptPaperStr).setScale(0, BigDecimal.ROUND_HALF_UP);
        String deptPaperValue = deptPaper.setScale(0).toString();//

        String posPaperStr = map.get("posPaper") == null ? "0" : map.get("posPaper").toString();//岗位纸质
        BigDecimal posPaper = "0E-8".equals(posPaperStr) ? new BigDecimal("0") : new BigDecimal(posPaperStr).setScale(0, BigDecimal.ROUND_HALF_UP);
        String posPaperValue = posPaper.setScale(0).toString();//


        String jobDesc = MapUtils.getString(map, "jobDesc", "");//工作说明
        String auditDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");//审批时间
        String baseOrgResPerson = MapUtils.getString(map, "baseOrgResPerson", "");//基层组织责任人

        String auth001 = getQuanXianValue(MapUtils.getString(map, "auth001", ""));//001权限(★ ▲ √ '')     '1'  五角    '5'  三角    '6'  对勾   '7' 空（取消授权）
        String qua001Str = map.get("qua001") == null ? "0" : map.get("qua001").toString();//
        BigDecimal qua001 = "0E-8".equals(qua001Str) ? new BigDecimal("0") : new BigDecimal(qua001Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua001Value = qua001.setScale(0).toString();//001数量
        String res001 = MapUtils.getString(map, "res001", "");//001学习要求(Ⅰ Ⅱ Ⅲ  '')     WHEN  '1' THEN  'Ⅰ'  when '2' then 'Ⅱ' when  '3' then 'Ⅲ'  else  '' end
        switch (res001) {
            case "Ⅰ":
                res001 = "1";
                break;
            case "Ⅱ":
                res001 = "2";
                break;
            case "Ⅲ":
                res001 = "3";
                break;
            case "":
                res001 = "0";
                break;
        }


        String auth002 = getQuanXianValue(MapUtils.getString(map, "auth002", ""));//
        String qua002Str = map.get("qua002") == null ? "0" : map.get("qua002").toString();//
        BigDecimal qua002 = "0E-8".equals(qua002Str) ? new BigDecimal("0") : new BigDecimal(qua002Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua002Value = qua002.setScale(0).toString();//
        String res002 = MapUtils.getString(map, "res002", "");//
        switch (res002) {
            case "Ⅰ":
                res002 = "1";
                break;
            case "Ⅱ":
                res002 = "2";
                break;
            case "Ⅲ":
                res002 = "3";
                break;
            case "":
                res002 = "0";
                break;
        }

        String auth003 = getQuanXianValue(MapUtils.getString(map, "auth003", ""));//
        String qua003Str = map.get("qua003") == null ? "0" : map.get("qua003").toString();//
        BigDecimal qua003 = "0E-8".equals(qua003Str) ? new BigDecimal("0") : new BigDecimal(qua003Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua003Value = qua003.setScale(0).toString();//
        String res003 = MapUtils.getString(map, "res003", "");//
        switch (res003) {
            case "Ⅰ":
                res003 = "1";
                break;
            case "Ⅱ":
                res003 = "2";
                break;
            case "Ⅲ":
                res003 = "3";
                break;
            case "":
                res003 = "0";
                break;
        }

        String auth004 = getQuanXianValue(MapUtils.getString(map, "auth004", ""));//
        String qua004Str = map.get("qua004") == null ? "0" : map.get("qua004").toString();//
        BigDecimal qua004 = "0E-8".equals(qua004Str) ? new BigDecimal("0") : new BigDecimal(qua004Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua004Value = qua004.setScale(0).toString();//
        String res004 = MapUtils.getString(map, "res004", "");//
        switch (res004) {
            case "Ⅰ":
                res004 = "1";
                break;
            case "Ⅱ":
                res004 = "2";
                break;
            case "Ⅲ":
                res004 = "3";
                break;
            case "":
                res004 = "0";
                break;
        }

        String auth005 = getQuanXianValue(MapUtils.getString(map, "auth005", ""));//
        String qua005Str = map.get("qua005") == null ? "0" : map.get("qua005").toString();//
        BigDecimal qua005 = "0E-8".equals(qua005Str) ? new BigDecimal("0") : new BigDecimal(qua005Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua005Value = qua005.setScale(0).toString();
        String res005 = MapUtils.getString(map, "res005", "");
        switch (res005) {
            case "Ⅰ":
                res005 = "1";
                break;
            case "Ⅱ":
                res005 = "2";
                break;
            case "Ⅲ":
                res005 = "3";
                break;
            case "":
                res005 = "0";
                break;
        }

        String auth006 = getQuanXianValue(MapUtils.getString(map, "auth006", ""));
        String qua006Str = map.get("qua006") == null ? "0" : map.get("qua006").toString();
        BigDecimal qua006 = "0E-8".equals(qua006Str) ? new BigDecimal("0") : new BigDecimal(qua006Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua006Value = qua006.setScale(0).toString();
        String res006 = MapUtils.getString(map, "res006", "");
        switch (res006) {
            case "Ⅰ":
                res006 = "1";
                break;
            case "Ⅱ":
                res006 = "2";
                break;
            case "Ⅲ":
                res006 = "3";
                break;
            case "":
                res006 = "0";
                break;
        }

        String auth007 = getQuanXianValue(MapUtils.getString(map, "auth007", ""));
        String qua007Str = map.get("qua007") == null ? "0" : map.get("qua007").toString();
        BigDecimal qua007 = "0E-8".equals(qua007Str) ? new BigDecimal("0") : new BigDecimal(qua007Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua007Value = qua007.setScale(0).toString();
        String res007 = MapUtils.getString(map, "res007", "");
        switch (res007) {
            case "Ⅰ":
                res007 = "1";
                break;
            case "Ⅱ":
                res007 = "2";
                break;
            case "Ⅲ":
                res007 = "3";
                break;
            case "":
                res007 = "0";
                break;
        }

        String auth008 = getQuanXianValue(MapUtils.getString(map, "auth008", ""));
        String qua008Str = map.get("qua008") == null ? "0" : map.get("qua008").toString();
        BigDecimal qua008 = "0E-8".equals(qua008Str) ? new BigDecimal("0") : new BigDecimal(qua008Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua008Value = qua008.setScale(0).toString();
        String res008 = MapUtils.getString(map, "res008", "");
        switch (res008) {
            case "Ⅰ":
                res008 = "1";
                break;
            case "Ⅱ":
                res008 = "2";
                break;
            case "Ⅲ":
                res008 = "3";
                break;
            case "":
                res008 = "0";
                break;
        }

        String auth009 = getQuanXianValue(MapUtils.getString(map, "auth009", ""));
        String qua009Str = map.get("qua009") == null ? "0" : map.get("qua009").toString();
        BigDecimal qua009 = "0E-9".equals(qua009Str) ? new BigDecimal("0") : new BigDecimal(qua009Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua009Value = qua009.setScale(0).toString();
        String res009 = MapUtils.getString(map, "res009", "");
        switch (res009) {
            case "Ⅰ":
                res009 = "1";
                break;
            case "Ⅱ":
                res009 = "2";
                break;
            case "Ⅲ":
                res009 = "3";
                break;
            case "":
                res009 = "0";
                break;
        }

        String auth010 = getQuanXianValue(MapUtils.getString(map, "auth010", ""));
        String qua010Str = map.get("qua010") == null ? "0" : map.get("qua010").toString();
        BigDecimal qua010 = "0E-10".equals(qua010Str) ? new BigDecimal("0") : new BigDecimal(qua010Str).setScale(0, BigDecimal.ROUND_HALF_UP);
        String qua010Value = qua010.setScale(0).toString();
        String res010 = MapUtils.getString(map, "res010", "");
        switch (res010) {
            case "Ⅰ":
                res010 = "1";
                break;
            case "Ⅱ":
                res010 = "2";
                break;
            case "Ⅲ":
                res010 = "3";
                break;
            case "":
                res010 = "0";
                break;
        }

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncArchiveBase '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                AType, baseOrgNumber,  fileCode, totalPaperValue,
                deptPaperValue, posPaperValue, jobDesc,
                auditDate,approval, baseOrgResPerson,
                auth001, qua001Value, res001,
                auth002, qua002Value, res002,
                auth003, qua003Value, res003,
                auth004, qua004Value, res004,
                auth005, qua005Value, res005,
                auth006, qua006Value, res006,
                auth007, qua007Value, res007,
                auth008, qua008Value, res008,
                auth009, qua009Value, res009,
                auth010, qua010Value, res010);

//        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCorpArchiveBase '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
//                baseOrgNumber,  fileCode, totalPaperValue,
//                deptPaperValue, posPaperValue, jobDesc,
//                auditDate,approval, baseOrgResPerson,
//                auth001, qua001Value, res001,
//                auth002, qua002Value, res002,
//                auth003, qua003Value, res003,
//                auth004, qua004Value, res004,
//                auth005, qua005Value, res005,
//                auth006, qua006Value, res006,
//                auth007, qua007Value, res007,
//                auth008, qua008Value, res008,
//                auth009, qua009Value, res009,
//                auth010, qua010Value, res010);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }
    private String getQuanXianValue(String qx) {
        String qxValue = "";
        qx = qx == null ? "" : qx;
        switch (qx) {
            case "★":
                qxValue = "1";
                break;
            case "▲":
                qxValue = "5";
                break;
            case "√":
                qxValue = "6";
                break;
            case "":
                qxValue = "7";
                break;
        }
        return qxValue;
    }
    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @param approvalType
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String approvalType) {
        String mainDeptCode = (String) bizObject.get("mainDeptCode");
        String activityCode ="";
        if ("01".equals(approvalType)){
            String manageDeptCode = (String) bizObject.get("manageDeptCode");
            if (mainDeptCode.equals(manageDeptCode)){
                activityCode="Activity11";
            }else{
                activityCode="Activity13";

            }
        }else if("03".equals(approvalType)) {
            String frameDeptCode = (String) bizObject.get("frameDeptCode");
            if (mainDeptCode.equals(frameDeptCode)){
                activityCode="Activity16";
            }else{
                activityCode="Activity20";
            }
        }


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = activityCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @param field
     * @param value
     * @param schemaCode
     * @return
     */
    private String existsBizObject(String field,String value,String schemaCode){

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where ").append(field).append("='").append(value).append("'");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-总公司档案 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();


        //关联档案
        data.put("relevFile",map.get("fileNumber"));
        //档案代码
        data.put("fileCode",map.get("fileCode"));
        //档案名称
        data.put("fileName",map.get("fileName"));

        //档案类型关联
        data.put("relevFileType",map.get("typeName"));
        //档案类型
        data.put("fileType",map.get("archTypeNumber"));
        //对应记录
        data.put("dyjl",map.get("record"));
        //关联基础代码
        data.put("relevBaseCode",map.get("basicCode"));
        //基础代码
        data.put("baseCode",map.get("baseCode"));
        //基础名称
        data.put("baseCodeName",map.get("name01"));
        //对应说明
        data.put("refDesc",map.get("refDes"));

        //备注
        data.put("remark",map.get("remarks"));
        //电子版
        data.put("elec",map.get("elec"));
        //说明
        data.put("explains",map.get("des"));

        //职能代码
        data.put("funCode",map.get("znCode"));
        //职能
        data.put("funName",map.get("znName"));

        //主责部门代码
        data.put("manaDeptNumber",map.get("manaDeptNumber"));
        //主责部门
        data.put("manaDeptName",map.get("manaDeptName"));

        //公司主责部门
        data.put("MainDeptId",map.get("MainDeptId"));
        //公司主责部门
        data.put("MainDeptName",map.get("MainDeptName"));
        //公司主责部门代码
        data.put("mainDeptCode",map.get("mainDeptCode"));

        //关联公司主责岗
        data.put("mainPositionId",map.get("mainPositionId"));
        //公司主责岗代码
        data.put("mainPositionCode",map.get("mainPositionCode"));
        //公司主责岗
        data.put("mainPostionName",map.get("mainPostionName"));
        //部门授权
        data.put("purview",map.get("purview"));
        //基层组织责任岗关联
        data.put("baseOrgResPosId",map.get("baseOrgResPosId"));
        //基层组织责任岗代码
        data.put("baseOrgResPosNumber",map.get("baseOrgResPosNumber"));
        //基层组织责任岗
        data.put("baseOrgResPosName",map.get("baseOrgResPosName"));
        //基层组织责任人
        data.put("baseOrgResPerson",map.get("baseOrgResPerson"));

        //纸质
        data.put("totalPaper",map.get("totalPaper"));
        //部门纸质
        data.put("deptPaper",map.get("deptPaper"));
        //岗位纸质
        data.put("posPaper",map.get("posPaper"));

        //要求
        data.put("res001",map.get("res001"));
        data.put("res002",map.get("res002"));
        data.put("res003",map.get("res003"));
        data.put("res004",map.get("res004"));
        data.put("res005",map.get("res005"));
        data.put("res006",map.get("res006"));
        data.put("res007",map.get("res007"));
        data.put("res008",map.get("res008"));
        data.put("res009",map.get("res009"));
        data.put("res010",map.get("res010"));
        data.put("res011",map.get("res011"));
        data.put("res012",map.get("res012"));
        data.put("res013",map.get("res013"));
        data.put("res014",map.get("res014"));
        data.put("res015",map.get("res015"));

        //权限
        data.put("auth001",map.get("auth001"));
        data.put("auth002",map.get("auth002"));
        data.put("auth003",map.get("auth003"));
        data.put("auth004",map.get("auth004"));
        data.put("auth005",map.get("auth005"));
        data.put("auth006",map.get("auth006"));
        data.put("auth007",map.get("auth007"));
        data.put("auth008",map.get("auth008"));
        data.put("auth009",map.get("auth009"));
        data.put("auth010",map.get("auth010"));
        data.put("auth011",map.get("auth011"));
        data.put("auth012",map.get("auth012"));
        data.put("auth013",map.get("auth013"));
        data.put("auth014",map.get("auth014"));
        data.put("auth015",map.get("auth015"));
        //数量
        data.put("qua001",map.get("qua001"));
        data.put("qua002",map.get("qua002"));
        data.put("qua003",map.get("qua003"));
        data.put("qua004",map.get("qua004"));
        data.put("qua005",map.get("qua005"));
        data.put("qua006",map.get("qua006"));
        data.put("qua007",map.get("qua007"));
        data.put("qua008",map.get("qua008"));
        data.put("qua009",map.get("qua009"));
        data.put("qua010",map.get("qua010"));
        data.put("qua011",map.get("qua011"));
        data.put("qua012",map.get("qua012"));
        data.put("qua013",map.get("qua013"));
        data.put("qua014",map.get("qua014"));
        data.put("qua015",map.get("qua015"));

        //工作说明
        data.put("jobDesc",map.get("refDes"));
        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);


        return data;
    }
}
